package com.panfeng.xcloud.gateway.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * http 响应 ZuulFilter过滤器
 *
 * @author xiaobo
 * @date 2018-03-15
 */
@Component
@Slf4j
public class HttpResponseFilter extends ZuulFilter {

	private static final String METHOD_POST = "post";

	@Override
	public String filterType() {
		return FilterConstants.POST_TYPE;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		return FilterCommand.isFilter(ctx,this);
	}

	@SuppressWarnings("deprecation")
	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String requestURI = request.getRequestURI();
		String method = request.getMethod();
		try {
			if(requestURI.indexOf("swagger") != -1 || requestURI.indexOf("api-docs") != -1){
				log.info(">>> 请求接口url:{},请求方式:{} 当前请求为swagger文档请求，不输出日志 <<<" ,requestURI ,method);
				TimerCounter.after(request);
				return null;
			}

			//包装HttpServletRequest可多次读取流信息
			/**
			request = new BufferedServletRequestWrapper(request);

			String postData = "";
			if (METHOD_POST.equalsIgnoreCase(method)) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
				postData = IOUtils.readAll(reader);
			}

			postData = StringUtils.isNotEmpty(postData) ? postData : "";
			 **/
			TimerCounter.after(request);
			log.info(">>> 请求接口url:{},请求方式:{}",requestURI, method);
			//ctx.setRequest(request);
			return null;
		} catch (Exception e) {
			log.error(">>> 请求接口url:{},请求方式:{}，zuul post 阶段异常：{}<<<" ,requestURI ,method,e.getMessage());
			e.printStackTrace();
			return null;
		}
	}

}
